package com.hpf.community.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hpf.community.annotations.MonitorLog;
import com.hpf.community.constants.CommunityConstants;
import com.hpf.community.enums.LogEnum;
import com.hpf.community.mapper.GoodsMapper;
import com.hpf.community.model.ActivityModel;
import com.hpf.community.model.GoodsModel;
import com.hpf.community.service.IActivityService;
import com.hpf.community.utils.CommonUtils;
import com.hpf.community.utils.PaginationResult;
import com.hpf.community.utils.StandardResult;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


/**
 *　　
 *   Activity 控制器    ${table.comment}
 *
 *   @author huangpengfei
 *   @since 2020-04-04
 */

@RestController
public class ActivityController {
    private final Logger logger = LoggerFactory.getLogger(ActivityController.class);

    @Autowired
    public IActivityService activityService;

    @Autowired
    public GoodsMapper goodsMapper;


    /**
     * 获取分页列表
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/activity")
    public StandardResult selectPage(@ModelAttribute ActivityModel activityModel,
                                     Integer pageSize, Integer pageNumber,
                                     String searchKey,
                                     Date startTime,
                                     Date endTime) {
		try {
			if (pageSize == null || pageNumber == null) {
				return StandardResult.faildCheck("缺少必要的分页参数！");
			}
	     	Page<ActivityModel> page = new Page<ActivityModel>(pageNumber, pageSize);
	     	Wrapper<ActivityModel> wrapper = new EntityWrapper<ActivityModel>();
	     	if(StringUtils.isNotBlank(searchKey)){
	     	    wrapper.like(ActivityModel.TITLE,searchKey);
	     	    wrapper.or();
	     	    wrapper.like(ActivityModel.DESCRIPTION,searchKey);
	     	    wrapper.or();
	     	    wrapper.like(ActivityModel.PLACE,searchKey);
	     	    wrapper.or();
	     	    wrapper.like(ActivityModel.COM_NAME,searchKey);
	     	    wrapper.or();
	     	    wrapper.like(ActivityModel.SUPPLIES,searchKey);
	     	}
            if(null != startTime){
                wrapper.andNew();
                wrapper.ge(ActivityModel.START_TIME,startTime);
            }
            if(null != endTime){
                wrapper.andNew();
                wrapper.le(ActivityModel.END_TIME,endTime);
            }
            if(StringUtils.isNotBlank(activityModel.getStatus())){
                wrapper.andNew();
                wrapper.eq(ActivityModel.STATUS,activityModel.getStatus());
            }
            if(StringUtils.isNotBlank(activityModel.getComId())){
                wrapper.andNew();
                wrapper.eq(ActivityModel.COM_ID,activityModel.getComId());
            }
	     	if(!StringUtils.equals(CommonUtils.getCurrentUserName(),CommunityConstants.ADMIN)){
	     	    //如果不是管理员，只能查看自己发起的活动
                wrapper.eq(ActivityModel.PUB_ID,CommonUtils.getCurrentUserId());
	     	}
	     	wrapper.eq(ActivityModel.IS_DELETE,CommunityConstants.USER_STATUS_ZC);
	     	activityService.selectPage(page, wrapper);
			return PaginationResult.ok(null, page.getRecords(), page.getTotal(), page.getPages());
		} catch (Exception e) {
			logger.error("异常信息:", e);
			return PaginationResult.faild(e);
		}
    }


    /**
     * 获取活动审核分页列表
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/activityCheck")
    @RequiresRoles("3")
    public StandardResult selectPageCheck(@ModelAttribute ActivityModel activityModel, Integer pageSize, Integer pageNumber,String searchKey,Date startTime,Date endTime) {
        try {
            if (pageSize == null || pageNumber == null) {
                return StandardResult.faildCheck("缺少必要的分页参数！");
            }
            Page<ActivityModel> page = new Page<ActivityModel>(pageNumber, pageSize);
            Wrapper<ActivityModel> wrapper = new EntityWrapper<ActivityModel>();
            if(StringUtils.isNotBlank(searchKey)){
                wrapper.like(ActivityModel.TITLE,searchKey);
                wrapper.or();
                wrapper.like(ActivityModel.DESCRIPTION,searchKey);
                wrapper.or();
                wrapper.like(ActivityModel.SUPPLIES,searchKey);
                wrapper.or();
                wrapper.like(ActivityModel.PLACE,searchKey);
                wrapper.or();
                wrapper.like(ActivityModel.COM_NAME,searchKey);
            }
            if(null != startTime){
                wrapper.andNew();
                wrapper.ge(ActivityModel.START_TIME,startTime);
            }
            if(null != endTime){
                wrapper.andNew();
                wrapper.le(ActivityModel.END_TIME,endTime);
            }
            if(StringUtils.isNotBlank(activityModel.getStatus())){
                wrapper.andNew();
                wrapper.eq(ActivityModel.STATUS,activityModel.getStatus());
            }
            if(StringUtils.isNotBlank(activityModel.getComId())){
                wrapper.andNew();
                wrapper.eq(ActivityModel.COM_ID,activityModel.getComId());
            }
            wrapper.andNew();
            wrapper.eq(ActivityModel.STATUS,CommunityConstants.ACTIVITY_CHECK_SPZ);//查待审批的数据
            wrapper.or();
            wrapper.eq(ActivityModel.STATUS,CommunityConstants.ACTIVITY_CHECK_BH);
            wrapper.andNew();
            wrapper.eq(ActivityModel.IS_DELETE,CommunityConstants.USER_STATUS_ZC);
            //只能角色3也就是管理员才能查看审批数据
            if(CommonUtils.getCurrentUser().getRole().equals(CommunityConstants.USER_ROLE_GLY)){
                activityService.selectPage(page, wrapper);
                return PaginationResult.ok(null, page.getRecords(), page.getTotal(), page.getPages());
            }else {
                return StandardResult.ok();
            }


        } catch (Exception e) {
            logger.error("异常信息:", e);
            return PaginationResult.faild(e);
        }
    }

	/**
     * 给小程序测试的接口
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/activityList")
    public StandardResult selectList(@ModelAttribute ActivityModel activityModel) {
		try {
			Wrapper<ActivityModel> wrapper = new EntityWrapper<ActivityModel>(activityModel);
			return StandardResult.ok(null, activityService.selectList(wrapper));
		} catch (Exception e) {
			logger.error("异常信息:", e);
			return StandardResult.faild(e);
		}
    }

     /**
      * 申请活动
      *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @PostMapping("/activity")
    @MonitorLog(value = "申请活动，修改活动或者审核活动，具体看详细日志",operateType = LogEnum.INSERT)
    public StandardResult insert(@ModelAttribute ActivityModel activityModel) {
		try {
            if(StringUtils.isBlank(activityModel.getId())){
                //为空代表是新增
                activityModel.setId(CommonUtils.getUUID());
                activityModel.setPubId(CommonUtils.getCurrentUserId());
                activityModel.setPubName(CommonUtils.getCurrentUserName());
                activityModel.setComId(CommonUtils.getCurrentUserComId());
                activityModel.setCreateUserid(CommonUtils.getCurrentUserId());
                activityModel.setCreateDatetime(new Date());
            }else {
                if(null != activityModel.getStartTime() && DateUtil.betweenMs(activityModel.getStartTime(),new Date()) > 0 && (StringUtils.equals(activityModel.getStatus(),CommunityConstants.ACTIVITY_CHECK_BH) || StringUtils.equals(activityModel.getStatus(),CommunityConstants.ACTIVITY_CHECK_TG))){
                    //无法审批，自动结束
                    activityModel.setStatus(CommunityConstants.ACTIVITY_CHECK_CSWP);
                    activityService.updateById(activityModel);
                    return StandardResult.faild("抱歉，您审批的活动"+activityModel.getTitle()+"已超过审批最后时间（不超过活动开始时间）");
                }
                activityModel.setModifyUserid(CommonUtils.getCurrentUserId());
                activityModel.setModifyDatetime(new Date());
            }
            activityService.insertOrUpdate(activityModel);
            return StandardResult.ok();
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }

    /**
         * 修改
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @PutMapping("/activity")
    public StandardResult updateById(@RequestBody ActivityModel activityModel) {
        try {
            activityService.updateById(activityModel);
            return StandardResult.ok();
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }

    /**
        * 通过id获取详情
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/activity/{id}")
    public StandardResult selectById(@PathVariable String id) {
		try {
		     return StandardResult.ok(activityService.selectById(id));
		} catch (Exception e) {
		     logger.error("异常信息:", e);
		     return StandardResult.faild(e);
		}
    }

    /**
     * 通过id删除数据
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @DeleteMapping("/activity/{id}")
    @MonitorLog(value = "撤销活动",operateType = LogEnum.DELETE)
    public StandardResult deleteById(@PathVariable String id) {
        try {
            ActivityModel model = activityService.selectById(id);
            model.setIsDelete(CommunityConstants.USER_STATUS_JY);
            activityService.updateById(model);
            return StandardResult.ok();
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }


    /**
     * 审批活动,与前端约定status传值：通过传2，驳回传3
     * @param: [activityModel]
     * @return: com.hpf.community.utils.StandardResult
     * @author: HPF
     * @date: 2020/4/12 21:36
     */
    @PutMapping("/pass")
    public StandardResult passActivity(@RequestBody ActivityModel activityModel){
        try{

            activityModel.setModifyDatetime(new Date());
            activityModel.setModifyUserid(CommonUtils.getCurrentUser().getId());
            activityService.updateById(activityModel);
            return StandardResult.ok();
        }catch(Exception e){
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }


    /**
     * 通过id获取详情
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/home/data")
    public StandardResult selectGoods(String type,Integer page) {
        try {
            Wrapper<GoodsModel> wrapper = new EntityWrapper<>();
            Page<GoodsModel> pages = new Page<>(page,10);
            wrapper.eq(GoodsModel.TYPE,type);
            List<GoodsModel> goodsModels = goodsMapper.selectPage(pages, wrapper);
            return StandardResult.ok(goodsModels);
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }
}
